package admin

import (
	"context"
	"fmt"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/module/admin/resourceLogic"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/utils/database"
	"grpc.getaway.adminspro.padmins.com/pkg/businessCommonQuery"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/utils"
	pbAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/admin"
	"strings"
)

func (rpc *admin) AdminResourceIndex(ctx context.Context, pb *pbAdmin.AdminResourceIndexReq) (*pbAdmin.AdminResourceIndexResp, error) {
	where, bindValue, _, order, e := businessCommonQuery.BuildByBusinessCommonQuery(pb.BusinessCommonQuery)

	if e != nil {
		return nil, businessError.ErrorInfoToRpcError(e)
	}

	Db := database.Db.GetDefaultDb(ctx)

	total, dbErr := Db.Find(fmt.Sprintf("select count(*) total from admin_resource where 1=1 %s", where), bindValue...)
	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	rows, dbErr := Db.Query(fmt.Sprintf("select * from admin_resource where 1=1 %s %s", where, order), bindValue...)
	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	resp := &pbAdmin.AdminResourceIndexResp{
		Rows:  make([]*pbAdmin.AdminResource, len(rows)),
		Total: total["total"].(int64),
	}

	ids := utils.ArrayColumn(rows, "id")
	list := resourceLogic.List()
	for i, row := range rows {
		businessCommonQuery.ListFormat(list, row)

		if row["resource"].(string) == "" {
			row["resource"] = strings.ReplaceAll(row["path"].(string), "/", ".")
		}

		if !utils.InArray(row["pid"], ids) {
			row["pid"] = int64(0)
		}

		resp.Rows[i] = &pbAdmin.AdminResource{
			Id:         row["id"].(int64),
			Pid:        row["pid"].(int64),
			Type:       int32(row["type"].(int64)),
			Path:       row["path"].(string),
			Resource:   row["resource"].(string),
			Title:      row["title"].(string),
			Icon:       row["icon"].(string),
			Remark:     row["remark"].(string),
			Badge:      row["badge"].(string),
			Weigh:      row["weigh"].(int64),
			Status:     int32(row["status"].(int64)),
			CreateTime: row["create_time"].(string),
			UpdateTime: row["update_time"].(string),
			StatusText: row["status_text"].(string),
			TypeText:   row["type_text"].(string),
			Name:       row["title"].(string),
		}
	}

	return resp, nil
}
